// pages/gjIndex/stepCar/stepCar.js
import config from "../../../config.js";
var util = require('../../../utils/util.js');
const openIdUrl = config;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    org: ["自费修车", "保险修车"],
    index: 0,
    uploadImg: "https://app.longchg.com/gudongcar/images/upload.jpg",
    //城市列表
    carList: [],
    carIndex: 0,
    typeList: [],
    companyList: [],
    typeIndex: 0,
    companyIndex: 0,
    backAddress: "",
    getAddress: "",
    getLatitude: '',
    getLongitude: '',
    backLatitude: '',
    backLongitude: '',
    orderType: 0,
    latitude: 0,
    longitude: 0,
    date: util.getDate(),
    date: util.getDate(),
    dateBack: util.getDate(),
    time: util.getMinute(),
    mintime: util.getMinute(),
    timeBack: util.getMinute(),
    // 是否上牌
    hasNo: true,
    tel: "",
    buList: [],
    buIndex: 0,
    isNeed: 0,
    chuType: 0,
    mark: '',
    car: null,
    user: null,
    userId: null,
    orderId: -1,
    order: null,
    canChange: 1,

  },

  select: function(e) {
    this.setData({
      index: e.detail.value
    })
  },

  selectAuto: function(e) {
    this.setData({
      autoIndex: e.detail.value
    })
  },

  selectQc: function(e) {
    this.setData({
      qcIndex: e.detail.value
    })
  },

  selectHc: function(e) {
    this.setData({
      hcIndex: e.detail.value
    })
  },

  selectQcDate: function(e) {
    this.setData({
      dateQc: e.detail.value
    })
  },

  selectQcTime: function(e) {
    this.setData({
      timeQc: e.detail.value
    })
  },

  submit: function() {

    if (this.data.orderId != -1) {
      console.log(this.data.orderId + "again:");
      wx.navigateTo({
        url: "./repair_bx?again=1&confirmType=2",
      })
    } else {
      console.log(this.orderId + "no:");
      wx.navigateTo({
        url: "./repair_bx?again=0&confirmType=2",
      })
    }
    // wx.navigateTo({
    //   url: './repair_bx',
    // })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var canChange = options.canChange;
    that.setData({
      canChange: canChange,
      time:util.getMinute(),
      tel: wx.getStorageSync("user").tel
    })

    //判断是否是再次下单或者更改订单类型
    var orderId = options.orderId;
    var userId = options.uid;

    console.log(orderId);
    console.log(userId);
    if (orderId != null) {
      that.setData({
        orderId: orderId
      })

      //获取订单详情
      that.orderDetail();
    }


  },

  orderDetail() {
    var that = this;
    //获取订单详情
    wx.request({
      url: openIdUrl.orderDetailUrl,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        id: this.data.orderId,
        isKeeper: 1
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          that.setData({
            order: res.data.data,
            user: res.data.data.order.account
          })
          that.setOrderData();
        } else {
          wx.showToast({
            title: '订单获取失败！',
            icon: 'none',
            duration: 1500
          })
          return false;
        }
      }

    })
  },
  setOrderData() {
    var that = this;
    //订单信息
    var order = that.data.order;
    console.log(order);
    // var service = that.data.order.service;
    that.setData({
      typeIndex: order.service.stepCarServiceType.typeId - 1,
      // user:order.account
      car: order.order.cars,
      index: order.service.repaireType.typeId - 1,
      backAddress: order.service.locationByReturnLocId1.name,
      getAddress: order.service.locationByPickupLocId.name,
      getLatitude: order.service.locationByPickupLocId.locLatitude,
      getLongitude: order.service.locationByPickupLocId.locLongitude,
      backLatitude: order.service.locationByReturnLocId1.locLatitude,
      backLongitude: order.service.locationByReturnLocId1.locLongitude,
      // orderType: 0,
      latitude: order.service.locationByPickupLocId.locLatitude,
      longitude: order.service.locationByPickupLocId.locLongitude,
      tel: order.service.tel,
      isNeed: order.service.stepCar!=null?1:0,
      date: order.service.connectionTime.substring(0, 10),
      time: order.service.connectionTime.substring(10, 16),
      dateBack: order.service.connectionTime.substring(0, 10),
      timeBack: order.service.connectionTime.substring(10, 16),
      idenCardA: order.service.idenCardA,
      idenCardB: order.service.idenCardB,
      licenseFr: order.service.licenseFr,
      licenseBa: order.service.licenseBa,
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    var item = wx.getStorageSync("userchoose");
    console.log(item);
    if (item != null&&item!="") {
      this.setData({
        user: item
      })

      if (item.licenseA != null && item.licenseB != null) {
        //设置默认车辆图片信息
        console.log(item);
        that.setData({
          licenseFr: item.licenseA,
          licenseBa: item.licenseB,
          isUploadIDFr: true,
          isUploadIDBa: true,
          isUploadFr: true,
          isUploadBa: true,
          isUploadFirst: false,
          isUploadBaFirst: false
        })
      }
    }

    var car = wx.getStorageSync("carchoose");
    if (car != null&car!="") {
      this.setData({
        car: car,
        isUploadIDFirst: false,
        isUploadBaIDFirst: false,
        idenCardA: car.wdxlicensePic,
        idenCardB: car.wdxlicensePicB,
      })
    }

    setTimeout(function() {
      that.getTypeList();
    }, 200);



    setTimeout(function() {
      that.getBuList();
    }, 500);

    setTimeout(function() {
      that.getComList();
    }, 600);


    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      }
    })


    var monthStr = (new Date().getMonth() + 1) < 10 ? "0" + (new Date().getMonth() + 1) : (new Date().getMonth() + 1);
    var dayStr = new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate();
    var dateStr = new Date().getFullYear() + "-" + monthStr + "-" + dayStr;
    this.setData({
      date: dateStr,
      dateBack: dateStr,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.setStorageSync("userchoose", null);
    wx.setStorageSync("carchoose", null);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  exchangeCar: function(e) {
    var userId = e.currentTarget.dataset.userid;
    if (userId) {
      wx.navigateTo({
        url: '../carList/carList?userId=' + userId,
      })
    }
  },
  exchangeCustomer: function(e) {
    wx.navigateTo({
      url: '../customerList/customerList',
    })
  },
  chooseMap: function() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        console.log(res);
        that.setData({
          getAddress: res.address
        })
      },
    })
  },
  chuChange: function(e) {
    this.setData({
      chuType: e.detail.value,
    })
  },
  dateChange: function(e) {
    var time = util.getMinute();
    var date = e.detail.value;
    var currentDate = util.getDate();
    var mintime = this.data.mintime;



    if (date != currentDate) {
      mintime = "";
    } else {
      mintime = util.getMinute();
      this.setData({
        time: time
      })
    }


    this.setData({
      date: e.detail.value,
      mintime: mintime,
    })
  },
  dateBackChange: function(e) {
    this.setData({
      dateBack: e.detail.value,
    })
  },
  isNeedChange: function(e) {
    this.setData({
      isNeed: e.detail.value,
    })
    console.log(this.data.isNeed);
  },

  buChange: function(e) {
    this.setData({
      buIndex: e.detail.value,
    })
  },

  timeChange: function(e) {
    this.setData({
      time: e.detail.value,
    })
  },
  timeBackChange: function(e) {
    this.setData({
      timeBack: e.detail.value,
    })
  },
  getComList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.insuranceComList,
      data: {
        start: 0,
        isNor: 0
      },
      success: function(res) {
        console.log("保险公司");
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          console.log(res.data.data);
          that.setData({
            companyList: res.data.data
          })
          
          try {
            for (var i = 0; i < that.data.companyList.length; i++) {
              var com = that.data.companyList[i];
              if (order.service.insuranceCom.insuranceId == com.insuranceId) {
                that.setData({
                  companyIndex: i,
                })
              }
            }

          } catch (e) {

          }
        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },
  getTypeList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.stepServiceTypeList,
      data: {
        start: 0,

      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          console.log(res.data.data);
          that.setData({
            typeList: res.data.data
          })

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },
  getBuList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.stepCarInfo,
      data: {
        start: 0,
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          console.log(res.data.data);
          that.setData({
            buList: res.data.data
          })

          try {

            console.log("item");
            var order = that.data.order;
            for (var i = 0; i < that.data.buList.length; i++) {
              var com = that.data.buList[i];
              console.log(order.service.stepCar.carId + '==' + com.carId);
              if (order.service.stepCar.carId == com.carId) {
                that.setData({
                  buIndex: i,
                })

                console.log("item" + i);
              }
            }

          } catch (e) {

          }

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },
  submit: function() {
    var that = this;
    if (that.data.user == null || that.data.car == null) {
      wx.showToast({
        title: "请选择客户及车辆",
        icon: 'none',
        mask: true,
        duration: 2000
      })
      return false;
    }
    if (that.data.getAddress == "") {
      wx.showToast({
        title: "请选择接车地点",
        icon: 'none',
        mask: true,
        duration: 2000
      })
      return false;
    }
    if (that.data.getAddress == "") {
      wx.showToast({
        title: "请选择还车地点",
        icon: 'none',
        mask: true,
        duration: 2000
      })
      return false;
    }
    if (that.data.tel == "") {
      wx.showToast({
        title: "请输入联系电话",
        icon: 'none',
        mask: true,
        duration: 2000
      })
      return false;
    }

    console.log("订单编号:" + that.data.orderId);

    var serviceType = that.data.typeList[that.data.typeIndex].typeId;
    wx.setStorageSync("serviceType", serviceType);
    var carId = that.data.car.cid;
    wx.setStorageSync("carId", carId);
    wx.setStorageSync("userId", that.data.user.aid);
    var addressReturn = that.data.getAddress;
    wx.setStorageSync("addressReturn", addressReturn);
    var tel = that.data.tel;
    wx.setStorageSync("tel", tel);
    var time = that.data.date + " " + that.data.time;
    var timeBack = that.data.dateBack + " " + that.data.timeBack;
    var repaireType = that.data.index == 0 ? 1 : 2;
    wx.setStorageSync("timePick", time);
    wx.setStorageSync("orderId", that.data.orderId);
    wx.setStorageSync("orderFrom", 2);
    wx.setStorageSync("repaireType", repaireType);
    wx.setStorageSync("timeReturn", timeBack);
    wx.setStorageSync("isNeed", that.data.isNeed);
    wx.setStorageSync("stepcar", that.data.buList[that.data.buIndex].carId);
    wx.setStorageSync("comId", that.data.companyList[that.data.companyIndex].insuranceId);
    wx.setStorageSync("backAddress", that.data.backAddress);
    wx.setStorageSync("getAddress", that.data.getAddress);
    wx.setStorageSync("getLatitude", that.data.getLatitude);
    wx.setStorageSync("getLongitude", that.data.getLongitude);
    wx.setStorageSync("backLatitude", that.data.backLatitude);
    wx.setStorageSync("backLongitude", that.data.backLongitude);
    wx.setStorageSync("idenCardA", that.data.idenCardA);
    wx.setStorageSync("idenCardB", that.data.idenCardB);
    wx.setStorageSync("licenseFr", that.data.licenseFr);
    wx.setStorageSync("licenseBa", that.data.licenseBa);


    if (that.data.orderId != -1) {
      wx.setStorageSync("reqairListAgain", this.data.order.service.repairServiceItems);
      console.log(this.data.order.service.repairServiceItems);
      wx.navigateTo({
        url: '../../repairDetail/repairSubmitDetail?isAgain=1',
      })
    } else {
      wx.navigateTo({
        url: '../../repairDetail/repairSubmitDetail',
      })
    }
    // wx.navigateTo({
    //   url: '../../repairDetail/repairSubmitDetail',
    // })
  },
  carChange: function(e) {
    this.setData({
      carIndex: e.detail.value,
    })
  },

  typeChange: function(e) {
    this.setData({
      typeIndex: e.detail.value,
    })
  },
  companyChange: function(e) {
    this.setData({
      companyIndex: e.detail.value,
    })
  },

  servChange: function(e) {
    this.setData({
      servIndex: e.detail.value,
    })
  },

  telChange: function(e) {
    this.setData({
      tel: e.detail.value,
    })
  },
  getChange: function(e) {
    this.setData({
      getAddress: e.detail.value,
    })
  },
  descChange: function(e) {
    this.setData({
      mark: e.detail.value,
    })
  },

  selectNo: function() {
    let flag = this.data.hasNo;
    if (flag) {
      this.setData({
        hasNo: false
      })
    } else {
      this.setData({
        hasNo: true
      })
    }
  },
  chooseMap: function() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        console.log(res);
        that.setData({
          getAddress: res.address,
          getLatitude: res.latitude,
          getLongitude: res.longitude,

        })
      },
    })
  },
  chooseMap2: function() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        console.log(res);
        that.setData({
          backAddress: res.address,
          backLatitude: res.latitude,
          backLongitude: res.longitude,
        })
      }
    })
  },
  selectCustomer: function(e) {
    wx.navigateTo({
      url: '../customerList/customerList',
    })
  },
  exchangeCar: function(e) {
    var id = e.currentTarget.dataset.userid;
    wx.navigateTo({
      url: '../carList/carList?userId=' + id,
    })
  },
  //行驶证
  uploadFr: function () {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          licenseFr: tempFilePaths,
          isUploadFr: true,
          isUploadFirst: false
        })

        console.log(that.data.licenseFr);


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.licenseFr[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function (res) {
            wx.hideLoading();
            res = JSON.parse(res.data);
            console.log(res);
            if (res.status == 200) {
              that.setData({
                isUploadFr: true,
              })
              that.data.licenseFr = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },

  uploadBa: function () {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          licenseBa: tempFilePaths,
          isUploadBa: true,
          isUploadBaFirst: false
        })


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.licenseBa[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function (res) {
            wx.hideLoading();
            console.log(res);
            res = JSON.parse(res.data);
            if (res.status == 200) {
              that.setData({
                isUploadBa: true,
              })
              that.data.licenseBa = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },
  //身份证正面
  uploadFrID: function () {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          idenCardA: tempFilePaths,
          isUploadIDFr: true,
          isUploadIDFirst: false
        })


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.idenCardA[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function (res) {
            wx.hideLoading();
            res = JSON.parse(res.data);
            console.log(res);
            if (res.status == 200) {
              that.setData({
                isUploadIDFr: true,
              })
              that.data.idenCardA = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },

  uploadBaID: function () {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          idenCardB: tempFilePaths,
          isUploadIDBa: true,
          isUploadBaIDFirst: false
        })


        //上传正面
        wx.showLoading({
          title: '正在上传',
        })
        wx.uploadFile({
          url: openIdUrl.uploadPic,
          filePath: that.data.idenCardB[0],
          name: 'picA',
          header: {
            "Cookie": wx.getStorageSync("session"),
            "content-type": "multipart/form-data"
          },
          success: function (res) {
            wx.hideLoading();
            console.log(res);
            res = JSON.parse(res.data);
            if (res.status == 200) {
              that.setData({
                isUploadIDBa: true,
              })
              that.data.idenCardB = res.fileName;
            } else {
              wx.showToast({
                title: res.message + '',
                icon: 'none',
                mask: true,
                duration: 2000
              })
            }
          }
        })
      },
    })
  },
})